import 'package:hongsheng/api/SPClassApiManager.dart';
import 'package:hongsheng/api/SPClassHttpCallBack.dart';
import 'package:hongsheng/app/SPClassApplicaion.dart';
import 'package:hongsheng/model/MatchAiListEntity.dart';
import 'package:hongsheng/pages/common/SPClassNoDataView.dart';
import 'package:hongsheng/utils/SPClassCommonMethods.dart';
import 'package:hongsheng/utils/SPClassDateUtils.dart';
import 'package:hongsheng/utils/SPClassImageUtil.dart';
import 'package:hongsheng/utils/SPClassNavigatorUtils.dart';
import 'package:hongsheng/utils/SPClassStringUtils.dart';
import 'package:hongsheng/utils/colors.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:hongsheng/widgets/SPClassBallFooter.dart';
import 'package:hongsheng/widgets/SPClassBallHeader.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'SPClassAiDetailPage.dart';
import 'SPClassAiPage.dart';


///AI预测
class SPClassCalculatePage extends StatefulWidget {
  final int type ; //0:历史  1:今天  2:明天
  const SPClassCalculatePage({Key ?key,this.type=0}) : super(key: key);

  @override
  _SPClassCalculatePageState createState() => _SPClassCalculatePageState();
}

class _SPClassCalculatePageState extends State<SPClassCalculatePage> {
  EasyRefreshController ?_controller ;
  String time = DateTime.now().add(Duration(days: -1)).toString();
  int page =1;
  List<MatchAiListDataEntity> dataList =[];
  var myEventBus;
  @override
  void initState() {
    _controller =new EasyRefreshController();
    spFunOnRefresh();
    myEventBus =  SPClassApplicaion.spProEventBus.on<String>().listen((event) {
      if(event.startsWith("aiRefresh:")){
        spFunOnRefresh();
      }
    });
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.custom(
      topBouncing: false,
      footer: SPClassBallFooter(
        textColor: Color(0xFF8F8F8F),
      ),
      header: SPClassBallHeader(
        textColor: Color(0xFF8F8F8F),
      ),
      controller:_controller,
      onRefresh: spFunOnRefresh,
      onLoad: spFunOnMore,
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildListDelegate(
              [
                dataList.length == 0 ? SPClassNoDataView(height: width(400),): Container()
              ]
          ),
        ),
        SliverList(
          delegate: SliverChildBuilderDelegate((c,i){
            return itemWidget(dataList[i]);
          },
            childCount:dataList.length
          ),
        ),
      ],
    );
  }

  Widget itemWidget(MatchAiListDataEntity data){
    return GestureDetector(
      onTap: (){
        SPClassNavigatorUtils.spFunPushRoute(context, SPClassAiDetailPage(matchId: data.spProGuessMatchId,matchType:SPClassAIPageState. matchType,));
      },
      child: Stack(
        children: <Widget>[
          Container(
            margin: EdgeInsets.symmetric(horizontal: width(12),vertical: width(4)),
            padding: EdgeInsets.symmetric(horizontal: width(12),vertical: width(8)),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    offset: Offset(0,0),
                    color: Color(0xFF000000).withOpacity(0.1),
                    blurRadius:width(6),),
                ]
            ),
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Image.asset(
                        SPClassImageUtil.spFunGetImagePath(SPClassAIPageState.matchType=='足球'?"ic_football":'ic_basketball'),
                        fit: BoxFit.fill, width: width(15)
                    ),
                    Text('  ${SPClassDateUtils.spFunDateFormatByString(data.spProStTime!, "MM-dd HH:mm")} ${data.spProLeagueName}',style: TextStyle(fontSize: sp(12)),),
                  ],
                ),
                SizedBox(height: width(10),),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          Text(SPClassStringUtils.spFunMaxLength(data.spProTeamOne!,length: 5),style: TextStyle(fontSize: sp(13)),),
                          SPClassImageUtil.spFunNetWordImage(
                              placeholder: "ic_team_one",
                              url:data.spProIconUrlOne??'',
                              width: width(31),
                              height:  width(31))
                        ],
                      ),
                    ),
                    Container(
                      width: width(70),
                      alignment: Alignment.center,
                      child:Text((data.spProStatus=='over'||data.spProStatus=='in_progress')?'${data.spProScoreOne}-${data.spProScoreTwo}':'VS',style: TextStyle(fontSize: sp(17),fontWeight: FontWeight.w600,color: data.spProStatus=='in_progress'?MyColors.main1:MyColors.grey_33),),
                    ),
                    Expanded(
                      flex: 1,
                      child: Row(
                        children: <Widget>[
                          SPClassImageUtil.spFunNetWordImage(
                              placeholder: "ic_team_two",
                              url:data.spProIconUrlTwo??'',
                              width: width(31),
                              height:  width(31)),
                          Text(SPClassStringUtils.spFunMaxLength(data.spProTeamTwo!,length: 5),style: TextStyle(fontSize: sp(13)),)
                        ],
                      ),
                    )

                  ],
                )
              ],
            ),
          ),
          Positioned(
            top: width(4),
            right: width(12),
            child: data.spProStatus=='over'?Container(
              width: width(40),
              height: width(25),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color:data.spProHitNum=='-1'?Colors.green:data.spProHitNum=='0'?MyColors.grey_99: MyColors.main1,
                borderRadius: BorderRadius.only(topRight: Radius.circular(4)),
              ),
              child: Text(data.spProHitNum=='-1'?'走':data.spProHitNum=='0'?'未中':'${data.spProCount}中${data.spProHitNum}',style: TextStyle(fontSize: sp(11),color: Colors.white),),
            ):data.spProStatus=='in_progress'?Container(
              width: width(40),
              height: width(25),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: MyColors.main1,
                borderRadius: BorderRadius.only(topRight: Radius.circular(4)),
              ),
              child: Text('进行中',style: TextStyle(fontSize: sp(11),color: Colors.white),),
            ):Container(),
          )
        ],
      ),
    );
  }

  Future spFunOnRefresh()async{
    page=1;
    dataList.clear();
    setState(() {
    });
    var params = {
      'type':widget.type==0?'history':widget.type==1?'today':'tomorrow',
      'page':page,
      // 'match_date':SPClassDateUtils.spFunDateFormatByString(time, "yyyy-MM-dd"),
      'match_type':SPClassAIPageState.matchType
    };
    SPClassApiManager.spFunGetInstance().spFunMatchAiList<MatchAiListEntity>(params:params,spProCallBack:SPClassHttpCallBack(
        spProOnSuccess: (result){
          SPClassApplicaion.spProEventBus.fire("updateNum:${result.spProMaxSum};${result.spProWeekSum};${result.spProYesterdayRed};${result.spProRecentRedNum}");
          dataList = result.spProList;
          _controller?.finishRefresh(noMore: false,success: true);
          _controller?.resetLoadState();
          setState(() {
          });
        },onError: (e){
      _controller?.finishRefresh(success: false);

    }
    ));
  }

  Future spFunOnMore()async{
    page++;
    var params = {
      'type':widget.type==0?'history':widget.type==1?'today':'tomorrow',
      'page':page,
      // 'match_date':SPClassDateUtils.spFunDateFormatByString(time, "yyyy-MM-dd"),
      'match_type':SPClassAIPageState.matchType
    };
    SPClassApiManager.spFunGetInstance().spFunMatchAiList<MatchAiListEntity>(params:params,spProCallBack:SPClassHttpCallBack(
        spProOnSuccess: (result){
          dataList.addAll(result.spProList);
          if(dataList.isEmpty){
            _controller?.finishLoad(noMore: true);
          }
          setState(() {
          });
        },onError: (e){
      _controller?.finishLoad(noMore: false);
      }
    ));
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    myEventBus.cancel();
  }
}
